<template>
  <div>
    <div class="mu_box">
      <el-form
        class="multiple_form"
        label-position="top"
        :model="form"
        ref="formName"
        :rules="rules"
        :inline="false"
        size="normal"
      >
        <el-form-item label="应用程序名称" prop="siddhiAppName">
          <el-select
            class="w100"
            size="small"
            filterable
            v-model="form.siddhiAppName"
            placeholder="请选择"
          >
            <!-- :disabled="
                  list
                    .map((i2) => i2.siddhiAppName)
                    .includes(item.siddhiAppName)
                " -->
            <el-option
              v-for="item in listSiddhiApps"
              :key="item.siddhiAppName"
              :label="item.siddhiAppName"
              :value="item.siddhiAppName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="流名称"
          prop="streamName"
          v-if="form.siddhiAppName"
        >
          <div class="stream_box">
            <el-select
              size="small"
              placeholder="请选择一个流"
              :disabled="form.listStreams.length == 0"
              filterable
              v-model="form.streamName"
            >
              <el-option
                v-for="item in form.listStreams"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
            <div class="time_interval">
              <span class="time_interval_title"> 时间间隔(ms) </span>
              <el-input
                :disabled="!form.streamName"
                size="small"
                placeholder="请输入时间间隔"
                v-model="form.timestampInterval"
              >
              </el-input>
            </div>
            <el-button
              @click="streamSele"
              plain
              size="small"
              icon="el-icon-circle-plus-outline"
              >添加流名称</el-button
            >
          </div>
        </el-form-item>
        <!-- {{ form.attributeConfList }} -->
        <div class="my_collapse" v-if="form.attributeConfList.length !== 0">
          <el-collapse
            :accordion="true"
            v-model="activeNames"
            @change="handleChange"
          >
            <el-collapse-item
              :name="item.name"
              v-for="(item, index) in form.attributeConfList"
              :key="item.name"
            >
              <template slot="title">
                <div>流名称：{{ item.name }}</div>
                <span
                  class="el-icon-delete-solid del_icon"
                  @click.stop="handleStrDel(index)"
                >
                </span>
              </template>
              <div>
                <el-form-item
                  v-for="(li, i) in item.listAttributes"
                  :key="li.name"
                >
                  <div slot="label">{{ li.name }} ({{ li.type[0] }})</div>
                  <!-- 对应三种不同类型 -->
                  <el-select
                    class="w100"
                    size="small"
                    placeholder="请选择"
                    @change="(val) => changeAttrType(val, li)"
                    v-model="li.attributesType"
                  >
                    <el-option
                      v-for="item in attributesTypeSele"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                  <div class="val_box">
                    <!-- 日期类型 -->
                    <el-form-item
                      :prop="
                        'attributeConfList.' +
                        index +
                        '.listAttributes.' +
                        i +
                        '.list'
                      "
                      :rules="[
                        {
                          required: li.attributesType != '',
                          message: '日期不能为空',
                          trigger: 'blur',
                        },
                      ]"
                      label="日期"
                      v-if="li.attributesType == 'CUSTOM_DATA_BASED'"
                    >
                      <el-input
                        @input="change($event)"
                        size="small"
                        placeholder="请输入日期"
                        v-model="li.list"
                      >
                      </el-input>
                    </el-form-item>
                    <!-- 来自... -->

                    <!-- primitiveType: "FLOAT" -->
                    <el-form-item
                      :prop="
                        'attributeConfList.' +
                        index +
                        '.listAttributes.' +
                        i +
                        '.length'
                      "
                      :rules="[
                        {
                          required: li.attributesType == 'PRIMITIVE_BASED',
                          message: '字符串长度不能为空',
                          trigger: 'blur',
                        },
                      ]"
                      label="字符串长度"
                      v-if="
                        li.attributesType == 'PRIMITIVE_BASED' &&
                        li.type[0] === 'STRING'
                      "
                    >
                      <el-input
                        size="small"
                        placeholder="请输入字符串长度"
                        v-model="li.length"
                      >
                      </el-input>
                    </el-form-item>
                    <div
                      class="primitive_list"
                      v-if="
                        li.attributesType == 'PRIMITIVE_BASED' &&
                        (li.type[0] == 'LONG' ||
                          li.type[0] == 'INT' ||
                          li.type[0] == 'DOUBLE' ||
                          li.type[0] == 'FLOAT')
                      "
                    >
                      <div class="primitive_item">
                        <el-form-item
                          label="来自"
                          :prop="
                            'attributeConfList.' +
                            index +
                            '.listAttributes.' +
                            i +
                            '.max'
                          "
                          :rules="[
                            {
                              required: li.attributesType === 'PRIMITIVE_BASED',
                              message: '来自不能为空',
                              trigger: 'blur',
                            },
                          ]"
                        >
                          <el-input
                            size="small"
                            placeholder="请输入"
                            v-model="li.max"
                          >
                          </el-input>
                        </el-form-item>
                      </div>
                      <div class="primitive_item" style="margin: 014px">
                        <el-form-item
                          label="少于"
                          :prop="
                            'attributeConfList.' +
                            index +
                            '.listAttributes.' +
                            i +
                            '.min'
                          "
                          :rules="[
                            {
                              required: li.attributesType === 'PRIMITIVE_BASED',
                              message: '少于不能为空',
                              trigger: 'blur',
                            },
                          ]"
                        >
                          <el-input
                            size="small"
                            placeholder="请输入"
                            v-model="li.min"
                          >
                          </el-input>
                        </el-form-item>
                      </div>
                      <!-- DOUBLE) -->
                      <!-- 目前只知道 type是DOUBLE FLOAT的需要添加小数位数 -->
                      <div
                        class="primitive_item"
                        v-if="li.type[0] == 'DOUBLE' || li.type[0] == 'FLOAT'"
                      >
                        <el-form-item
                          label="小数位数"
                          :prop="
                            'attributeConfList.' +
                            index +
                            '.listAttributes.' +
                            i +
                            '.precision'
                          "
                          :rules="[
                            {
                              required: li.attributesType == 'PRIMITIVE_BASED',
                              message: '小数位数不能为空',
                              trigger: 'blur',
                            },
                          ]"
                        >
                          <el-input
                            size="small"
                            placeholder="请输入"
                            v-model="li.precision"
                          >
                          </el-input>
                        </el-form-item>
                      </div>
                    </div>

                    <!-- 正则类型 -->
                    <el-form-item
                      label="Pattern"
                      v-if="li.attributesType == 'REGEX_BASED'"
                      :prop="
                        'attributeConfList.' +
                        index +
                        '.listAttributes.' +
                        i +
                        '.pattern'
                      "
                      :rules="[
                        {
                          required: li.attributesType == 'REGEX_BASED',
                          message: 'Pattern不能为空',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        size="small"
                        placeholder="请输入"
                        v-model="li.pattern"
                      >
                      </el-input>
                    </el-form-item>
                    <!-- 下拉框类型 -->
                    <el-form-item
                      label="类型"
                      v-if="
                        li.attributesType == 'PROPERTY_BASED' &&
                        li.type[0] !== 'OBJECT'
                      "
                      :prop="
                        'attributeConfList.' +
                        index +
                        '.listAttributes.' +
                        i +
                        '.property'
                      "
                      :rules="[
                        {
                          required: li.attributesType == 'PROPERTY_BASED',
                          message: 'property不能为空',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-select
                        filterable
                        class="w100"
                        size="small"
                        placeholder="请选择"
                        v-model="li.property"
                      >
                        <el-option
                          v-for="item in typeOptionsTime"
                          :key="item"
                          :label="item"
                          :value="item"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                </el-form-item>
              </div>
              <span
                :class="
                  !item.isTime ? 'el-icon-arrow-down' : 'el-icon-arrow-up'
                "
                class="senior_option"
                @click="setIsTime(item)"
              >
                高级配置
              </span>
              <el-collapse-transition>
                <el-form-item label="时间间隔(ms)" v-if="item.isTime">
                  <el-input
                    size="small"
                    placeholder="请输入时间间隔"
                    v-model="item.timestampInterval"
                  >
                  </el-input>
                </el-form-item>
              </el-collapse-transition>
            </el-collapse-item>
          </el-collapse>
        </div>
      </el-form>
    </div>
    <div class="btns">
      <el-button size="small" v-if="isDel" @click="handleDel">删除</el-button>
      <el-button size="small" type="primary" @click="onSubmit">完成</el-button>
    </div>
  </div>
</template>

<script>
import Datepicker from "@/components/Datepicker";
import { mapGetters } from "vuex";
import {
  attributesTypeSele,
  propertyBasedGenerationOptionsForString,
  propertyBasedGenerationOptionsForInt,
  propertyBasedGenerationOptionsForLong,
  propertyBasedGenerationOptionsForDouble,
  propertyBasedGenerationOptionsForFloat,
  typeOptions,
} from "@/utils/local";
import { listStreams, listAttributes } from "@/api/siddhi";
import { setAttrTypeVal } from "../js/index";
import _ from "lodash";
export default {
  components: {
    Datepicker,
  },
  computed: {
    ...mapGetters(["listSiddhiApps"]),
  },
  props: {
    AnalogSourceObj: {
      type: Array,
      default: () => [],
    },
    index: {
      type: Number,
      default: null,
    },
  },
  watch: {
    // 应用程序下拉框选择或者赋值之后触发
    "form.siddhiAppName"(val) {
      const obj = this.AnalogSourceObj.find(
        (i2) =>
          i2.siddhiAppName == this.form.siddhiAppName &&
          i2.simulationType == "RANDOM_DATA_SIMULATION"
      );
      // 存在直接回显,不存在的 置空
      console.log(obj, "存在就编辑");
      if (obj) {
        this.isDel = true;
        this.form.attributeConfList = _.cloneDeep(obj).attributeConfList;
      } else {
        this.isDel = false;
        this.form.attributeConfList = [];
      }
      this.siddhiSele(val);
    },
  },
  data() {
    return {
      isDel: false,
      typeOptionsTime: [],
      activeNames: "",
      attributesTypeSele: attributesTypeSele,
      typeOptions: typeOptions,
      rules: {
        siddhiAppName: [{ required: true, message: "请选择应用程序" }],
        // streamName: [{ required: true, message: "请选择流" }],
      },
      typeValue: "Random",
      form: {
        siddhiAppName: "",
        streamName: "",
        listAttributes: [],
        listStreams: [],
        attributeConfList: [],
        timestampInterval: "",
        simulationType: "RANDOM_DATA_SIMULATION", //类型===随机的 cvg
      },
    };
  },
  methods: {
    handleDel() {
      this.$emit("handleDelSiddhiType", this.form);
    },
    // changeSiddhiAppName(val) {
    //   const isList = this.AnalogSourceObj.map(
    //     (i2) => i2.siddhiAppName
    //   ).includes(this.form.siddhiAppName);
    //   if (isList) {
    //     this.$msg("当前应用程序已存在,可选择编辑");
    //     return;
    //   }
    // },
    setIsTime(item) {
      this.$set(item, "isTime", !item.isTime);
    },
    changeAttrType(attrType, li) {
      const type = li.type[0];
      // 不同类型的不同 下拉数组
      switch (type) {
        case "BOOL":
          this.typeOptionsTime = propertyBasedGenerationOptionsForString;
          break;
        case "STRING":
          this.typeOptionsTime = propertyBasedGenerationOptionsForString;
          li.property = "ADDRESS";
          break;
        case "INT":
          this.typeOptionsTime = propertyBasedGenerationOptionsForInt;
          li.property = "DAY";
          break;
        case "LONG":
          this.typeOptionsTime = propertyBasedGenerationOptionsForLong;
          li.property = "DAY";
          break;
        case "FLOAT":
          this.typeOptionsTime = propertyBasedGenerationOptionsForFloat;
          break;
        case "DOUBLE":
          this.typeOptionsTime = propertyBasedGenerationOptionsForDouble;
          li.property = "DAY";
          break;
        default:
          // this.typeOptionsTime = [];
          break;
      }
      // 不同类型的 不同默认v-model
      switch (attrType) {
        case "CUSTOM_DATA_BASED":
          li.list = setAttrTypeVal(attrType, type);
          break;
        case "REGEX_BASED":
          li.pattern = setAttrTypeVal(attrType, type);
          break;
        case "PROPERTY_BASED":
          break;
        default:
          break;
      }
      // 切换的时候,会保留上一个输入框的校验,这里要清除
      this.clearValidate();

      // li.list = staticValue;
    },
    // 输入框赋默认值,需要手动渲染,不然无法输入 (也可以在表单内添加默认的字段)
    change() {
      this.$forceUpdate();
    },
    clearValidate(fromName) {
      // 移除表单项的校验结果。传入待移除的表单项的 prop 属性或者 prop 组成的数组，如不传则移除整个表单的校验结果
      this.$nextTick(() => {
        this.$refs["formName"].clearValidate(fromName);
      });
    },
    resetFields() {
      // 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      this.form = this.$options.data().form;
      // this.$nextTick(() => {
      this.$refs["formName"].resetFields();
      // });
    },
    handleStrDel(index) {
      this.form.attributeConfList.splice(index, 1);
    },
    // 添加流并获取流下的属性
    streamSele(val) {
      if (!this.form.streamName) {
        this.$msg("请选择流");
        return;
      }
      const isStrName = this.form.attributeConfList.some((item) => {
        return item.name == this.form.streamName;
      });
      if (isStrName) {
        this.activeNames = this.form.streamName;
        this.$msg("已存在流,请勿重复添加");
        return;
      }
      listAttributes({
        siddhiAppName: this.form.siddhiAppName,
        streamName: this.form.streamName,
      }).then((res) => {
        const { data } = res;
        const listAttributes = data.map((item) => {
          return {
            ...item,
            isCheck: false,
            value: "",
            type: [item.type],
            attributesType: "", //当前选中属性 类型下拉
          };
        });
        this.form.attributeConfList.push({
          name: this.form.streamName,
          listAttributes,
          timestampInterval: this.form.timestampInterval,
          isTime: this.form.timestampInterval ? true : false,
        });
        // 打开当前选中的
        this.activeNames = this.form.streamName;
      });
    },
    // 获取流
    siddhiSele(val) {
      // 从vuex获取流
      this.form.siddhiState = this.$store.getters["siddhi/getsiddhiFlow"](val);
      if (!val) {
        return;
      }
      listStreams(val).then((res) => {
        const { data } = res;
        // 新建的时候在清空
        if (this.index === null) {
          this.form.attributeConfList = [];
          this.form.listAttributes = [];
        }
        this.form.streamName = "";

        this.form.listStreams = data.map((item) => {
          return {
            name: item,
          };
        });
        // 清空一下表单验证
        this.clearValidate("streamName");
      });
    },
    handleChange(val) {
      if (val) {
        console.log(val);
      }
    },
    onSubmit() {
      this.$refs["formName"].validate((valid) => {
        if (valid) {
          this.$emit("onSubmit", this.form);
          this.resetFields();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    picked() {},
  },
};
</script>


<style scoped lang='scss'>
.senior_option {
  margin-top: 10px;
  float: right;
  cursor: pointer;
  color: #2680d2;
}
.btns {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  /* padding: 0 30px; */
  position: absolute;
  bottom: 30px;
  right: 20px;
  width: 100%;
}
.mu_box {
  height: calc(100vh - 160px);
  overflow: auto;
  border-bottom: 1px solid #e4e4e4;
  /deep/ .el-form-item__label {
    width: 100% !important;
  }
  .primitive_list {
    display: flex;
    align-items: center;
    width: 100%;
    .primitive_item {
      display: flex;
      flex-direction: column;
      width: 100%;
      .title {
        font-size: 14px;
        color: #666666;
        justify-content: space-between;
      }
    }
  }
  .val_box {
    padding: 0 20px;
  }
  .my_collapse {
    margin-top: 16px;
    margin-bottom: 20px;
    .del_icon {
      color: #666666;
      position: absolute;
      right: 20px;
      top: 50%;
      transform: translate(0, -50%);
    }
    /deep/ .el-collapse {
      border: 1px solid #e4e4e4;
      .el-form-item__label {
        font-weight: 400;
      }
      .el-collapse-item {
        .el-collapse-item__header {
          background-color: #f9f9f9;
          padding-left: 10px;
          border-bottom: 1px solid #e4e4e4;
          height: 34px;
          line-height: 34px;
          position: relative;
        }
        .el-collapse-item__wrap {
          padding: 0 10px;
          background-color: #f9f9f9;
        }
        background-color: #f9f9f9;
      }
    }
  }
  .stream_box {
    display: flex;
    align-items: center;
    .time_interval {
      display: flex;
      margin-left: 34px;
      margin-right: 10px;
      .time_interval_title {
        margin-right: 6px;
        font-size: 14px;
        color: #666666;
        white-space: nowrap;
      }
    }
  }
  /deep/ .el-form-item {
    margin-bottom: 0;
  }
  .add_simulation {
    height: 47px;
    background-color: #e6f7ff;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    margin-top: 64px;

    div {
      color: #2680d2;
      font-size: 14px;
      margin-left: 3px;
      &:first-child {
        margin-left: 0;
        font-size: 15px;
      }
    }
  }

  .multiple_form {
    padding: 0 30px;

    .time_stamp_show {
      background-color: #f9f9f9;
      padding: 10px;
      padding-top: 0;
      .data_picker {
        display: flex;
        align-items: center;
        .line {
          margin: 0 10px;
          background-color: #dcdfe6;
          width: 12px;
          height: 1px;
        }
      }
    }

    .time_title_arr {
      cursor: pointer;
      display: flex;
      align-items: center;
    }
    /deep/ .el-form-item__label {
      padding-bottom: 0;
    }
  }
}
</style>